package com.akk.business;

import com.akk.PayConstants;
import com.akk.common.enums.Enums;
import com.akk.module.access.entity.AccessBind;
import com.akk.module.access.service.AccessService;
import com.akk.module.avs.entity.AvsCustomer;
import com.akk.module.avs.entity.AvsPayCashBind;
import com.akk.module.avs.entity.AvsPayOrder;
import com.akk.module.avs.entity.AvsPayVip;
import com.akk.module.avs.enums.AvsPayVipStatus;
import com.akk.module.avs.model.request.DepositRequest;
import com.akk.module.avs.model.request.HkPaymentNotifyRequest;
import com.akk.module.avs.service.AvsCustomerService;
import com.akk.module.avs.service.AvsPayCashBindService;
import com.akk.module.avs.service.AvsPayOrderService;
import com.akk.module.avs.service.AvsPayVipService;
import com.akk.module.hkpay.model.*;
import com.akk.module.hkpay.service.HkPayService;
import com.akk.module.hkpay.util.FtpUtil;
import com.akk.module.hkpay.util.HkUtils;
import com.akk.module.hkpay.util.QRUtils;
import com.akk.module.hxt.utils.HxtUtils;
import com.akk.utils.IDUtils;
import com.akk.utils.RestResponse;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.net.util.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class AvsHkPayBusiness {

    @Autowired
    private HkPayService hkPayService;

    @Autowired
    private AvsPayCashBindService cashBindService;

    @Autowired
    private AvsPayOrderService orderService;

    @Autowired
    private AvsCustomerService customerService;

    @Autowired
    private AccessService accessService;

    @Autowired
    private AvsPayVipService vipService;

    @Autowired
    private AvsPayBusiness payBusiness;

    @Value("${server.url}")
    private String serverUrl;

    @Autowired
    private FtpUtil ftpUtil;

    public RestResponse createOrder(String cashBindId, String orderNum, String payerId, String type, String openId) {
        List<AvsPayOrder> orders = orderService.findByOrderNum(orderNum);
        if (orders.isEmpty())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "订单不存在");
        AvsPayOrder order = orders.get(0);
        if (!order.getPayerId().equals(payerId))
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "非法请求");
        AvsCustomer customer = customerService.findByCustomerId(payerId);
        if (customer == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户信息不存在");
        if (customer.getHkSubMerId() == null) {
            return RestResponse.build("101", "商户信息尚未注册");
        } else if (customer.getHkFileUpload() != 1)
            return RestResponse.build("102", "用户尚未提交商户照片");
        if (!type.equals("alipay") && !type.equals("wechat")) {
            AccessBind cashBind = accessService.findAccessBindById(cashBindId);
            if (cashBind == null)
                return RestResponse.build(RestResponse.AVS_ERROR_CODE, "银行卡信息有误");
            order.setCashCardNo(cashBind.getCardNum());
            order.setPayBank(cashBind.getCardName());
            orderService.update(order);
        }
        HkCreateOrderRequest createOrderRequest = new HkCreateOrderRequest();
        createOrderRequest.setAmount(order.getAmountTotal().toString());
        createOrderRequest.setGoodsName(order.getRemark());
        createOrderRequest.setMerchOrderNo(order.getOrderNum());
        createOrderRequest.setCertsNo(customer.getIdCard());
        createOrderRequest.setRemark(order.getRemark());
        createOrderRequest.setFrontEndUrl(serverUrl + "/pay/alipay-success.html?payerId=" + payerId + "&appId=" + customer.getAppId());
        if ("alipay".equals(type)) {
            createOrderRequest.setPayType("027"); // 支付宝 027   微信  014
            createOrderRequest.setOpenId(payerId);
//            createOrderRequest.setSubAppId("wx9973ed900292d2d8");
        } else if ("wechat".equals(type)) {
            createOrderRequest.setPayType("014"); // 支付宝 027   微信  014
            createOrderRequest.setOpenId(openId);
            createOrderRequest.setSubAppId("wx9973ed900292d2d8");
        } else if ("quick".equals(type)) {
            createOrderRequest.setPayType("016"); // 无卡快捷消费(返网页)
            createOrderRequest.setOpenId(payerId);
            createOrderRequest.setFrontEndUrl(serverUrl + "/pay/pay-success.html?payerId=" + payerId + "&appId=" + customer.getAppId());
        } else {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "未知的交易类型");
        }
        createOrderRequest.setBackEndUrl(serverUrl + "/thmlfApi/avs/hkpay/paymentnotify");
        RestResponse restResponse = hkPayService.createOrder(createOrderRequest);
        if (restResponse.getCode().equals(String.valueOf(HttpStatus.SC_OK))) {
            HkCreateOrderResponse response = (HkCreateOrderResponse) restResponse.getResult();
            Map result = new HashMap();
            if (response.getIsHtml().equals("0") || response.getPayType().equals("009") || response.getPayType().equals("011")) {
                result.put("type", "qr");
                result.put("qrUrl", QRUtils.makeQR(response.getQrURL(), 0, 0));
            } else if (response.getIsHtml().equals("1")) {
                result.put("type", "html");
                result.put("html", response.getHtml());
            } else if (response.getPayType().equals("027")) {
                result.put("type", "qr");
                result.put("qrUrl", QRUtils.makeQR(response.getPayInfo(), 0, 0));
            } else if (response.getPayType().equals("014")) {
                result.put("type", "wechat");
                result.put("payInfo", Base64.encodeBase64String(response.getPayInfo().getBytes()));
            }
            return RestResponse.build(result);
        }
        return restResponse;
    }

    // 商户入网
    public RestResponse regMer(HkSubmitRequest request) {
        AvsCustomer customer = customerService.findByCustomerId(request.getPayerId());
        if (customer == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户信息不存在");
        List<AvsPayCashBind> cashBinds = cashBindService.findByIsDepositAndPayerId(1, customer.getCustomerId());
        if (cashBinds.isEmpty())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "无结算卡信息");
        Map<String, String> appHead = new HashMap<>();
        appHead.put("Version", "100");
        appHead.put("TransType", "S1050");
        appHead.put("SerialNo", UUID.randomUUID().toString().replace("-", ""));
        appHead.put("DataTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        Map<String, String> appBody = new HashMap<String, String>();
        appBody.put("institutionNo", PayConstants.HK_ORGAN_NUMBER);
        appBody.put("merName", "爱卡卡极速收款商户-" + request.getMerName());
        appBody.put("merNameShort", "极速收款-" + request.getSubMerName());
        appBody.put("merAddress", request.getMerAddress());
        appBody.put("merLegalName", customer.getCustomerName());
        appBody.put("merLegalNo", customer.getIdCard());
        appBody.put("merLegalMobilePhone", request.getPhone());
        appBody.put("posAreaCode", request.getAddressCode());
        appBody.put("mbiBankNo", request.getBankNumber());
        appBody.put("mbiBankName", request.getBankName());
        appBody.put("mbiAccountUser", customer.getCustomerName());
        appBody.put("mbiAccountNo", request.getCardNumber());
        appBody.put("mbiType", "对私");
        appBody.put("busiNo", "0311,789");
        appBody.put("rateId", "5402,5403");
        appBody.put("extMerNo", customer.getCustomerId());
        appBody.put("liquidateModle", "2");
        appBody.put("defaultWalletAccount", "1");
        appBody.put("sign", "empty");
        Map<String, Object> appMap = new HashMap<String, Object>();
        appMap.put("AppHead", appHead);
        appMap.put("AppBody", appBody);
        String json = new Gson().toJson(appMap);
        String[] nos = {"sign", "mbiType", "extMerNo", "liquidateModle", "defaultWalletAccount"};
        String url = HkUtils.createSortUrl(json, nos);
        url += PayConstants.HK_REG_MER_KEY;
        String signByCustomer = DigestUtils.md5Hex(url).toUpperCase();
        appBody.put("sign", signByCustomer);
        json = new Gson().toJson(appMap);
        String result = HkUtils.URLPost(PayConstants.HK_REG_MER_URL, json);
        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
        JsonObject body = jsonObject.getAsJsonObject("AppBody");
        RestResponse restResponse;
        if ("S1050_00".equals(body.get("RetCode").getAsString())) {
            customer.setHkSubMerId(body.get("merNo").getAsString());
            customer.setHkPosNo(body.get("posHcunitcode").getAsString());
            customerService.update(customer);
            return RestResponse.build(customer.getHkSubMerId());
        } else
            restResponse = RestResponse.build(RestResponse.AVS_ERROR_CODE, body.get("RetMessage").getAsString());
        return restResponse;
    }

    // 机构提现到商户
    public RestResponse withdrawalToMer(String orderNum, String payerId) {
        AvsCustomer customer = customerService.findByCustomerId(payerId);
        if (customer == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户信息不存在");
        List<AvsPayOrder> orders = orderService.findByOrderNum(orderNum);
        if (orders.isEmpty())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "订单信息不存在");
        AvsPayOrder order = orders.get(0);
        if (!order.getPayerId().equals(payerId))
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户信息不正确");
        List<AvsPayCashBind> cashBinds = cashBindService.findByIsDepositAndPayerId(1, payerId);
        if (cashBinds.isEmpty())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "无结算卡信息");
//        return withdrawalToCard(orderNum,payerId);
        if (order.getHkDespoit() != null && order.getHkDespoit() == 1) {
            // 提现到商户已完成，进行提现到卡
            return withdrawalToCard(orderNum, payerId);
        } else if (order.getHkDespoit() != null && order.getHkDespoit() == 2) {
            // 提现到卡已完成，提现操作已完成
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "订单提现操作已完成");
        } else {
            // 未开始提现
            HkWithdrawalRequest request = new HkWithdrawalRequest();
            request.setAmount((int) (order.getRealAmount() * 100) + "");
            request.setInNo(customer.getHkSubMerId());
            request.setOutNo(PayConstants.HK_ORGAN_NUMBER);
            request.setInstNo(PayConstants.HK_ORGAN_NUMBER);
            request.setOrderNo(IDUtils.getUniqueNum14());
            request.setOrderTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getCreateDate()));
            request.setTradeSequence(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
            request.setRemark(order.getRemark());
            request.setUseT0Amount("Y");
            request.setType("I2M");
            RestResponse restResponse = hkPayService.withdrawal(request);
            if (restResponse.getCode().equals(String.valueOf(HttpStatus.SC_OK))) {
                order.setHkDespoit(1);
                orderService.update(order);
                restResponse = withdrawalToCard(orderNum, payerId);
            }
            return restResponse;
        }
    }

    // 从商户提现到卡
    public RestResponse withdrawalToCard(String orderNum, String payerId) {
        AvsCustomer customer = customerService.findByCustomerId(payerId);
        if (customer == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户信息不存在");
        List<AvsPayOrder> orders = orderService.findByOrderNum(orderNum);
        if (orders.isEmpty())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "订单信息不存在");
        AvsPayOrder order = orders.get(0);
        if (!order.getPayerId().equals(payerId))
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户信息不正确");
        List<AvsPayCashBind> cashBinds = cashBindService.findByIsDepositAndPayerId(1, payerId);
        if (cashBinds.isEmpty())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "无结算卡信息");
        RestResponse updateCard = updateCard(customer, cashBinds.get(0));
        if (!updateCard.getCode().equals(String.valueOf(HttpStatus.SC_OK)))
            return updateCard;
        order.setCashCardNo(cashBinds.get(0).getCardNum());
        order.setCollecBank(cashBinds.get(0).getBankName());
        HkWithdrawalRequest request = new HkWithdrawalRequest();
        request.setAmount((int) (order.getRealAmount() * 100) + "");
        request.setInNo(customer.getHkSubMerId());
        request.setOutNo(customer.getHkSubMerId());
        request.setInstNo(PayConstants.HK_ORGAN_NUMBER);
        request.setOrderNo(order.getOrderNum());
        request.setOrderTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getCreateDate()));
        request.setTradeSequence(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        request.setRemark(order.getRemark());
        request.setUseT0Amount("Y");
        request.setType("M2C");
        RestResponse restResponse = hkPayService.withdrawal(request);
        if (restResponse.getCode().equals(String.valueOf(HttpStatus.SC_OK))) {
            restResponse = RestResponse.build("提现发起成功");
            order.setHkDespoit(2);
            order.setTransDate(new Date());
            order.setStatus(Enums.OrderStatusEnum.SUCCESS_DEPOSIT.getValue());
        }
        orderService.update(order);
        return restResponse;
    }

    // 修改结算卡
    public RestResponse updateCard(AvsCustomer customer, AvsPayCashBind cashBind) {
        if (customer.getHkPosNo() == null || customer.getHkPosNo().length() < 1)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户终端号有误");
        Map<String, String> appHeader = new HashMap<>();
        appHeader.put("Version", "100");
        appHeader.put("TransType", "S1059"); // 修改银行卡
        appHeader.put("SerialNo", UUID.randomUUID().toString().replace("-", ""));
        appHeader.put("DataTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        Map<String, String> appBody = new HashMap<String, String>();
        appBody.put("institutionNo", PayConstants.HK_ORGAN_NUMBER);
        appBody.put("posNo", customer.getHkPosNo());
        appBody.put("name", cashBind.getHoldName());
        appBody.put("cardNo", cashBind.getCardNum());
        appBody.put("bankNo", "304651015799");
        appBody.put("defaultWalletAccount", "1");
        appBody.put("sign", "empty");
        Map<String, Object> appMap = new HashMap<>();
        appMap.put("AppHead", appHeader);
        appMap.put("AppBody", appBody);
        String json = new Gson().toJson(appMap);
        String[] nos = {"sign", "mbiType", "defaultWalletAccount"};
        String url = HkUtils.createSortUrl(json, nos);
        url += PayConstants.HK_REG_MER_KEY;
        String signByCustomer = DigestUtils.md5Hex(url).toUpperCase();
        appBody.put("sign", signByCustomer);
        json = new Gson().toJson(appMap);
        String result = HkUtils.URLPost(PayConstants.HK_REG_MER_URL, json);
        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
        JsonObject body = jsonObject.get("AppBody").getAsJsonObject();
        if (body.has("RetCode") && body.get("RetCode").getAsString().equals("S1059_00")) {
            // 成功
            return RestResponse.build("修改成功");
        }
        return RestResponse.build(RestResponse.AVS_ERROR_CODE, body.get("RetMessage").getAsString());
    }

    // 支付通知
    public void paymentNotify(HttpServletRequest request) {
        HkPaymentNotifyRequest notifyRequest = new Gson().fromJson(HxtUtils.readContent(request), HkPaymentNotifyRequest.class);

        List<AvsPayOrder> orders = orderService.findByOrderNum(notifyRequest.getMerchOrderNo());
        if (orders.isEmpty())
            return;
        AvsPayOrder order = orders.get(0);
        if (order.getStatus() >= Enums.OrderStatusEnum.FAILED.getValue())
            return;
        if (notifyRequest.getRespCode().equals("00")) {
            order.setStatus(Enums.OrderStatusEnum.SUCCESS_PAYED.getValue());
            order.setTransDate(new Date());
        } else {
            order.setStatus(Enums.OrderStatusEnum.FAILED.getValue());
            order.setTransDate(new Date());
        }
        orderService.update(order);
        // VIP缴费
        if (order.getRemark().equals(PayConstants.VIP_CASH)) {
            order.setStatus(Enums.OrderStatusEnum.VIP_SUCCESS.getValue());
            List<AvsPayVip> vips = vipService.findByUserId(order.getPayerId());
            if (vips.isEmpty())
                return;
            AvsPayVip payVip = vips.get(0);
            payVip.setStatus(AvsPayVipStatus.VipStatus.VIP.getValue());
            Date nowDate = new Date();
            Calendar c = Calendar.getInstance();
            //一年后
            c.setTime(nowDate);
            c.add(Calendar.YEAR, 1);
            Date nextYear = c.getTime();
            payVip.setPayTime(nowDate);
            payVip.setEndTime(nextYear);
            payVip.setMoney(order.getAmountTotal());
            vipService.update(payVip);
        } else {
            // 提现
            DepositRequest depositRequest = new DepositRequest();
            depositRequest.setSummary(order.getRemark());
            depositRequest.setIsRedeposit(0);
            depositRequest.setPayerId(order.getPayerId());
            depositRequest.setAmount(order.getRealAmount().toString());
            depositRequest.setOrderNum(order.getOrderNum());
            RestResponse restResponse = payBusiness.deposit(depositRequest);
            if (!restResponse.getCode().equals(String.valueOf(HttpStatus.SC_OK))) {
                System.out.println("error:" + new Gson().toJson(restResponse));
            } else {
//                orders = orderService.findByOrderNum(notifyRequest.getMerchOrderNo());
//                order = orders.get(0);
//                order.setStatus(Enums.OrderStatusEnum.SUCCESS_DEPOSIT.getValue());
//                order.setTransDate(new Date());
//                order.setFinishDate(new Date());
//                orderService.update(order);
            }
        }
    }

    public RestResponse createWechatPayUrl(String cashBindId, String orderNum, String payerId) throws UnsupportedEncodingException {
        AvsCustomer customer = customerService.findByCustomerId(payerId);
        if (customer == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户信息不存在");
        if (customer.getHkSubMerId() == null) {
            return RestResponse.build("101", "商户信息尚未注册");
        } else if (customer.getHkFileUpload() != 1)
            return RestResponse.build("102", "用户尚未提交商户照片");
        String url = serverUrl + "/pay/wechat.html?cashBindId=" + cashBindId + "&orderNum=" + orderNum + "&payerId=" + payerId + "&type=wechat";
        url = Base64.encodeBase64String(url.getBytes());
        String callback = serverUrl + "/thmlfApi/avs/hkpay/openId?uri=" + url;
        callback = URLEncoder.encode(callback, "UTF-8");
        String url1 = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9973ed900292d2d8&redirect_uri=" + callback + "&response_type=code&scope=snsapi_base#wechat_redirect";
        String result = QRUtils.makeQR(url1, 0, 0);
        return RestResponse.build(result);
    }

    public RestResponse getCode() {
//        String codeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9973ed900292d2d8&redirect_uri=http%3A%2F%2F028wkf.cn/thmlfApi/avs/hkpay/openId&response_type=code&scope=snsapi_base#wechat_redirect";
//        HttpResponse resultMap = HttpClientHelper.doHttp(codeUrl, HttpClientHelper.GET, "utf-8", null,"60000");
//        if (resultMap.getStatusCode() == HttpStatus.SC_OK){
//            return RestResponse.build(resultMap.getRspStr());
//        }
        return RestResponse.build(RestResponse.AVS_ERROR_CODE, "获取OPENID失败");
    }

    public void getOpenId(String code, String uri, HttpServletResponse response) {
        try {
            StringBuffer buffer = new StringBuffer();
            String openIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx9973ed900292d2d8&secret=f43c7dee307322c1897117e94a500817&code=" + code + "&grant_type=authorization_code";
            //发送get请求
            URL serverUrl = new URL(openIdUrl);
            HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();
            System.out.println("openIdUrl:" + openIdUrl);
            //将返回的输入流转换成字符串
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            String result = buffer.toString();
            System.out.println(result);
            if (result.length() > 0) {
                JsonObject object = new JsonParser().parse(result).getAsJsonObject();
                if (object.has("openid")) {
                    System.out.println("uri:" + uri);
                    String openId = object.get("openid").toString();
                    uri = URLDecoder.decode(uri, "UTF-8");
                    System.out.println("openId:" + openId);
                    System.out.println("base64 uri:" + uri);
//                    BASE64Decoder decoder = new BASE64Decoder();
                    uri = new String(new BASE64Decoder().decodeBuffer(uri), "UTF-8");
                    System.out.println("uri:" + uri);
                    uri = uri + "&openId=" + openId.replaceAll("\"", "");
                    System.out.println("open uri:" + uri);
                    response.sendRedirect(uri);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 订单查询
    public RestResponse orderQuery(AvsPayOrder order) {
        HkOrderQueryRequest request = new HkOrderQueryRequest();
        request.setMerchOrderNo(order.getOrderNum());
        RestResponse restResponse = hkPayService.hkOrderQuery(request);
        if (restResponse.getCode().equals(String.valueOf(HttpStatus.SC_OK))) {
            return RestResponse.build("1001", "此订单已经结算成功，如果长时间未到账，请联系客服处理。");
        }
        return restResponse;
    }

    // 进度查询
    public RestResponse depositProgress(AvsPayOrder order) {
        HkOrderQueryRequest request = new HkOrderQueryRequest();
        request.setMerchOrderNo(order.getOrderNum());
        RestResponse restResponse = hkPayService.hkOrderQuery(request);
        if (restResponse.getCode().equals(String.valueOf(HttpStatus.SC_OK))) {
            return RestResponse.build(4);
        }
        return RestResponse.build(-1);
    }

    // 商户入网资料提交
    public RestResponse submitMerInfo(HkSubmitRequest request) {
        return regMer(request);
    }

    // 提交照片
    public RestResponse submitPhoto(HkSubmitMerPhotoRequest request, BindingResult result) {
        if (result.hasErrors())
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, result.getFieldError().getDefaultMessage());
        AvsCustomer customer = customerService.findByCustomerId(request.getPayerId());
        if (customer == null || StringUtils.isEmpty(customer.getHkSubMerId()))
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户信息有误。");
        String dateTime = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String random = String.valueOf((int) (Math.random() * 1000000 + 100000));
        boolean upload1 = ftpUtil.uploadFile(request.getIdCardPos(), dateTime + "_" + customer.getHkSubMerId() + "_053_" + random + ".jpg");
        boolean upload2 = ftpUtil.uploadFile(request.getIdCardOpp(), dateTime + "_" + customer.getHkSubMerId() + "_054_" + random + ".jpg");
        boolean upload3 = ftpUtil.uploadFile(request.getBankCardPos(), dateTime + "_" + customer.getHkSubMerId() + "_051_" + random + ".jpg");
        boolean upload4 = ftpUtil.uploadFile(request.getBankCardOpp(), dateTime + "_" + customer.getHkSubMerId() + "_052_" + random + ".jpg" );
        if (upload1 && upload2 && upload3 && upload4) {
            customer.setHkFileUpload(1);
            customerService.update(customer);
            return RestResponse.build("上传成功");
        }
        return RestResponse.build(RestResponse.AVS_ERROR_CODE, "文件上传失败，请稍后重试");
    }

    public RestResponse userNameWithIdCard(String payerId) {
        AvsCustomer customer = customerService.findByCustomerId(payerId);
        if (customer == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户信息不存在");
        if (customer.getIdCard() == null
                || customer.getIdCard().equals("")
                || customer.getIdCard().toLowerCase().equals("null")
                || customer.getIdCard() == null
                || customer.getIdCard().equals("")
                || customer.getIdCard().toLowerCase().equals("null")) {
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户信息有误，请联系客服修改");
        }
        Map<String, String> result = new HashMap<>();
        result.put("name", customer.getCustomerName());
        result.put("idCard", customer.getIdCard().substring(0, 4) + "********" + customer.getIdCard().substring(customer.getIdCard().length() - 4, customer.getIdCard().length()));
        return RestResponse.build(result);
    }

    public RestResponse userMerRegInfo(String payerId) {
        AvsCustomer customer = customerService.findByCustomerId(payerId);
        if (customer == null)
            return RestResponse.build(RestResponse.AVS_ERROR_CODE, "用户信息不存在");
        if (customer.getHkSubMerId() == null || customer.getHkSubMerId().equals(""))
            return RestResponse.build("101", "尚未注册");
        else if (customer.getHkFileUpload() != 1)
            return RestResponse.build("102", "已注册未提交资料");
        else if (customer.getHkFileUpload() == 1)
            return RestResponse.build("103","商户信息已经提交");
        return RestResponse.build(RestResponse.AVS_ERROR_CODE, "未知信息");
    }
}
